package com.kimwu.kill.mall.item.web.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kimwu.kill.mall.item.common.vo.ItemVO;
import com.kimwu.kill.mall.item.web.entity.Item;
import com.kimwu.kill.mall.item.web.entity.ItemStock;
import com.kimwu.kill.mall.item.web.service.IItemService;
import com.kimwu.kill.mall.item.web.service.IItemStockService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author KimWu
 * @Description ：
 */
@Slf4j
@Component
@RabbitListener(
        //绑定队列
        bindings = @QueueBinding(
                //需要指定queue的名字
                value = @Queue(
                        //配置队列名称
                        value = "${rabbitmq.dlx.name}",
                        //是否是一个可删除的临时队列 --> 消息持久化
                        autoDelete = "false"
                ),
                //配置交换器
                exchange = @Exchange(
                        //指定交换器名称
                        value = "${rabbitmq.dlx.exchange}",
                        //指定具体的交换器类型,有常量类指定
                        type = ExchangeTypes.DIRECT
                ),
                //路由键
                key = "${rabbitmq.dlx.routingkey}"
        )
)
public class ItemListen {

    @Resource
    private IItemService itemService;
    @Resource
    private IItemStockService itemStockService;

    /**
     * 接受消息的方法，采用消息队列监听机制
     */
    @RabbitHandler
    public void pay(String msg, Message message, Channel channel) throws Exception {
        log.info("consumers 接受到了 rabbitmq 消息 {}", msg);
        try {
            ItemVO itemVO = JSONObject.parseObject(msg, ItemVO.class);

            Item item = itemService.getById(itemVO.getId());
            ItemStock itemStock = itemStockService.getOne(new QueryWrapper<ItemStock>().eq("item_id", itemVO.getId()));
            item.setSales(itemVO.getSales());
            itemStock.setStock(itemVO.getStock());
            itemService.updateById(item);
            itemStockService.updateById(itemStock);

            //消费者手动ack机制
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        } catch (IOException e) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }

    }
}
